package cn.sytton.taffecloud.common.base.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Json工具类
 *
 * @author skyrock
 */
@Slf4j
public class JsonUtil {

    public static String getString(Object o){
        if (o == null) {
            return "";
        } else {
            try {
                return new ObjectMapper().writeValueAsString(o);
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
                return "";
            }
        }
    }

    public static <T> T getEntity(String json, Class<T> cls){
        if (StringUtils.hasText(json)) {
           try {
                return new ObjectMapper().readValue(json, cls);
            } catch (IOException e) {
               log.error(e.getMessage(), e);
                return null;
            }
        } else {
            return null;
        }
    }

    public static Map<String, Object> getEntity(String json){
        if (json == null) {
            return null;
        } else if ("".equals(json)){
            return new HashMap<>();
        } else {
            try {
                return new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>() {
                });
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                return null;
            }
        }
    }

    public static <T> T getArray(String json, Class<T> cls) {
        ObjectMapper mapper = new ObjectMapper();

        try {
            return new ObjectMapper().readValue(json, cls);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

//    public static void main(String[] args) {
//        String json = "[\"1E3B5399-17F7-480A-AFEB-1D71AC90E6CA\",\"1B463535-74DD-4E71-81CE-B5D4F19EA512\"]";
//
//        String[] arr = Json.getArray(json, String[].class);
//
//        System.out.println(arr[0]);
//    }
}
